package com.lixueju.security.box.web.authentication.filter;

import com.alibaba.fastjson.JSONObject;
import com.lixueju.security.box.core.enums.LoginTypeEnum;
import com.lixueju.security.box.core.model.request.WeixinDecodeLoginRequest;
import com.lixueju.security.box.core.properties.SecurityBoxConstants;
import com.lixueju.security.box.core.utils.HttpUtil;
import com.lixueju.security.box.web.authentication.SecurityBoxAuthenticationFilter;
import com.lixueju.security.box.web.authentication.SecurityBoxAuthenticationToken;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lixueju
 * @since 2019/11/18 13:20
 **/
public class WeixinDecodeSecurityBoxAuthenticationFilter extends SecurityBoxAuthenticationFilter {

    public WeixinDecodeSecurityBoxAuthenticationFilter() {
        super(SecurityBoxConstants.DEFAULT_LOGIN_PROCESSING_URL_WEIXIN_DECODE);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException, IOException {
        if (postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        String bodyParm = HttpUtil.obtainParameter(request);
        WeixinDecodeLoginRequest weixinDecodeLoginRequest = JSONObject.parseObject(bodyParm, WeixinDecodeLoginRequest.class);
        weixinDecodeLoginRequest.setLoginType(LoginTypeEnum.weixinDecode.code());
        SecurityBoxAuthenticationToken authRequest = new SecurityBoxAuthenticationToken(weixinDecodeLoginRequest);
        // Allow subclasses to set the "details" property
        setDetails(request, authRequest);
        return this.getAuthenticationManager().authenticate(authRequest);
    }
}
